<?php namespace Admin\Controller; 
use Hdphp\Controller\Controller;
//文章控制器
class ArtController extends Controller{
	protected $artModel;
	//构造函数
	public function __init()
	{
		//检测用户是否登陆
		//p($_SESSION['uid']);exit;
		if(!isset($_SESSION['aid'])) header('Location: '.U('Login/index'));
		$this->artModel = new  \Common\Model\Art;
	}
	
	public function index(){
		$page = Page::row(2)->make(Db::table('article')->where("is_recycle=0")->count());//设置分页
//		print_r($page);exit;
		View::with('page',$page);
		
		$arts = $this->artModel->myget();
		View::with('arts',$arts);
		View::make();
	}
	
	public function add(){
		if(IS_POST){
			
			if($this->artModel->myadd()){
				View::success('发布文章成功',U('Art/index'));
			}
			View::error($this->artModel->getError());
		}
		
		
		
		//1.获取所有分类
		$cateModel = new \Common\Model\Cate;
		$cates = $cateModel->get();
		//树状显示
		$cates = Data::tree($cates ,'cname','cid','pid');
		
		//2.获取所有的标签
		$tagModel = new \Common\Model\Tag;
		$tags = $tagModel->get();
		
		View::with('cates',$cates);
		View::with('tags',$tags);
		View::make();
		
	}
	
	//编辑
	public function edit(){
		//三、修改
		if(IS_POST){
			if(!$this->artModel->edit()) View::error($this->model->getError());
		    View::success("修改成功");
		}
		//一、处理标签和分类数据
		$tagModel = new \Common\Model\Tag;
		View::with('tagData',$tagModel->get());
		$cateModel = new \Common\Model\Cate;
		View::with('cateData',Data::tree($cateModel->get(),'cname'));
	
		//二、获取旧数据
		$aid = Q('get.aid',0,'intval');
		$oldData = Db::table('article')
				->join('article_data','aid','=','article_aid')
				->where("aid={$aid}")
				->first();
//		p($oldData);
		View::with('oldData',$oldData);
		//当前文章所选择的标签
		$arcTagModel = new \Common\Model\ArcTag;
		$tids = $arcTagModel->where("article_aid={$aid}")->lists('tag_tid');
		//如果用户没有选择标签，那么标签的默认值为NULL，in_array判断就会有问题，所以给默认值为空数组
		$tids = $tids ? $tids : array();
		View::with('tids',$tids);
			
		
        View::make();
    }
	
	//删除到回收站
	public function del(){
		//p(Q('get.'));exit;
		$aid=Q('get.aid',0,'intval');
		$is_recycle = $this->artModel->where("aid=$aid")->pluck('is_recycle');
		
		if($is_recycle==0){
			if($this->artModel->save(['aid'=>$aid,'is_recycle'=>1])){
				View::success('已删除到回收站');
			}
			View::success('删除到回收站失败');
		}else{//如果已经在回收站了 就彻底删除
			
			if($this->artModel->where("aid=$aid")->delete()){
				Db::table('article_data')->where("article_aid",$aid)->delete();
				View::success('已删除文章');
			}
			View::success($this->artModel-getError());
			
		}
		
		
	}
	
	//回收站
	public function recycle(){
		$arts = $this->artModel->myget(true);
		View::with('arts',$arts);
		View::make();
	    
	}
	//回收站 还原recovery
	public function recovery(){
		$aid=Q('get.aid',0,'intval');
		$this->artModel->save(['aid'=>$aid,'is_recycle'=>0]);
		go(U('Art/index'));
	}
}
